//
//  UserAccountViewModel.swift
//  AsiaWeiBo
//
//  Created by 史亚洲 on 16/1/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    
    var userAccount: UserAccount?
    
    override init() {
        userAccount = UserAccount.loadUserAccount()
        super.init()
    }
    //用户是否登录的标记,只读属性,计算型属性
    var userLogin: Bool {
    
    
    return userAccount?.access_token != nil
    
    }
    
    //从缓存中获取token
    var token: String? {
    
    return userAccount?.access_token
    
    }
    
    
    
    //2.获取用户授权信息,需要回调是否成功
    func loadAccessToken(code: String,finished: (isSuccess: Bool) -> ()) {
        
        //2.1url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        /*
        
        必选	类型及范围	说明
        client_id	true	string	申请应用时分配的AppKey。
        client_secret	true	string	申请应用时分配的AppSecret。
        grant_type	true	string	请求的类型，填写authorization_code
        
        grant_type为authorization_code时
        必选	类型及范围	说明
        code	true	string	调用authorize获得的code值。
        redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
        
        */
        //2.2请求参数
        let parameters = ["client_id": client_id,"client_secret": client_secret,"grant_type": "authorization_code","code": code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        
        //2.3设置JSON解析数据
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            
            guard let dict = result as? [String :AnyObject] else {
                
                print("数据格式不合法")
                
                //执行失败的回调
                finished(isSuccess: false)
                return
                
                
            }
            
            //获取用户信息
            let count = UserAccount(dict: dict)
            self.loadUserInfo(count,finished: finished)
            
            
            }) { (_, error) -> Void in
                
                finished(isSuccess: false)
                print(error)
        }
        
        
        
    }

    
    //==========获取用户信息,读取接口,根据用户ID获取用户信息=========
    private func loadUserInfo(account: UserAccount,finished: (isSuccess: Bool) ->()){
        
        //1.准备url
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": account.access_token!,"uid": account.uid!]
        
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            guard let dict = result as? [String : AnyObject] else{
                
                print("数据格式不合法")
                finished(isSuccess: false)
                return
                
            }
            
            let name = dict["name"] as? String
            let avatar_large = dict["avatar_large"] as? String
            
            //需要的用户信息就全部获取到
            account.name = name
            account.avatar_large = avatar_large
            print(account)
            account.saveAccount()
            //执行成功的回调
            finished(isSuccess: true)
            
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
    


}
